package pro.xxh.servlet;

import pro.xxh.JdbcUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(urlPatterns = "/xxhLogin")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("u");
        String password = request.getParameter("p");

        System.out.println("usernsme=" + username);
        System.out.println("password=" + password);

        String code = request.getParameter("c");
        HttpSession session = request.getSession();
        Object ccc = session.getAttribute("ccc");

        boolean isTrue = code != null && code.equals(ccc);
        if (!isTrue) {
            PrintWriter writer = response.getWriter();
            writer.write("code is error");
            writer.flush();
            writer.close();
            return;
        }

        String sql = "SELECT id FROM `user` where username=? and `password`=?";
        Integer id = JdbcUtils.select(sql, Integer.class, username, password);
        String message = id != null && id > 0 ? "登录成功!" : "登录失败！";

        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.write(message);
        writer.flush();
        writer.close();
    }
}